package client;


import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import clientCommunicationHandler.ClientServerMsgHandler;

public class TelnetClientHandler extends SimpleChannelUpstreamHandler{
	private static final Logger logger = Logger.getLogger(TelnetClientHandler.class.getName());
	private StringBuilder newMsg = new StringBuilder();
	private ClientServerMsgHandler serverHandler = new ClientServerMsgHandler();

	@Override
	public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
		if (e instanceof ChannelStateEvent){
			logger.info(e.toString());
		}
		super. handleUpstream(ctx,e);
	}

	@Override
	public void messageReceived( ChannelHandlerContext ctx, MessageEvent e){

		//print out the live received from the server
		System.err.println(e.getMessage());	
		String tServerMsg = e.getMessage().toString();
		String tMsg = null;
		if(!tServerMsg.equals("\0")){
			newMsg.append(tServerMsg+"\n");
			System.out.println("messageReceived function===="+tServerMsg);
//			System.out.println("**"+tServerMsg+"++++");
		}
		else{
//		System.out.println("recieved message: "+newMsg.toString());
			tMsg = newMsg.toString();
			newMsg = new StringBuilder();
//			System.out.println("messageRecieved");
//			System.out.println("the msg is: "+tMsg);
			serverHandler.parseServerMsg(tMsg);
		}
	}

	@Override
	public void exceptionCaught(
			ChannelHandlerContext ctx, ExceptionEvent e) {
		logger.log(
				Level.WARNING,
				"Unexpected exception from downstream.",
				e.getCause());
		e.getChannel().close();
	}



}
